1- INSTALAÇÃO E CARREGAMENTO DOS PACOTES NECESSÁRIOS

pacotes <- c("tidyverse","sf","tmap","rgdal","rgeos","adehabitatHR","knitr",
             "kableExtra")

if(sum(as.numeric(!pacotes %in% installed.packages())) != 0){
  instalador <- pacotes[!pacotes %in% installed.packages()]
  for(i in 1:length(instalador)) {
    install.packages(instalador, dependencies = T)
    break()}
  sapply(pacotes, require, character = T) 
} else {
  sapply(pacotes, require, character = T) 
}
## Carregando pacotes exigidos: tidyverse
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v ggplot2 3.3.5     v purrr   0.3.4
## v tibble  3.1.6     v dplyr   1.0.7
## v tidyr   1.1.4     v stringr 1.4.0
## v readr   2.1.1     v forcats 0.5.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
## Carregando pacotes exigidos: sf
## Linking to GEOS 3.9.1, GDAL 3.2.1, PROJ 7.2.1; sf_use_s2() is TRUE
## Carregando pacotes exigidos: tmap
## Carregando pacotes exigidos: rgdal
## Carregando pacotes exigidos: sp
## Please note that rgdal will be retired by the end of 2023,
## plan transition to sf/stars/terra functions using GDAL and PROJ
## at your earliest convenience.
## 
## rgdal: version: 1.5-28, (SVN revision 1158)
## Geospatial Data Abstraction Library extensions to R successfully loaded
## Loaded GDAL runtime: GDAL 3.2.1, released 2020/12/29
## Path to GDAL shared files: C:/Users/italo/OneDrive/Documentos/R/win-library/4.1/rgdal/gdal
## GDAL binary built with GEOS: TRUE 
## Loaded PROJ runtime: Rel. 7.2.1, January 1st, 2021, [PJ_VERSION: 721]
## Path to PROJ shared files: C:/Users/italo/OneDrive/Documentos/R/win-library/4.1/rgdal/proj
## PROJ CDN enabled: FALSE
## Linking to sp version:1.4-6
## To mute warnings of possible GDAL/OSR exportToProj4() degradation,
## use options("rgdal_show_exportToProj4_warnings"="none") before loading sp or rgdal.
## Overwritten PROJ_LIB was C:/Users/italo/OneDrive/Documentos/R/win-library/4.1/rgdal/proj
## Carregando pacotes exigidos: rgeos
## rgeos version: 0.5-9, (SVN revision 684)
##  GEOS runtime version: 3.9.1-CAPI-1.14.2 
##  Please note that rgeos will be retired by the end of 2023,
## plan transition to sf functions using GEOS at your earliest convenience.
##  GEOS using OverlayNG
##  Linking to sp version: 1.4-6 
##  Polygon checking: TRUE
## Carregando pacotes exigidos: adehabitatHR
## Carregando pacotes exigidos: deldir
## deldir 1.0-6      Nickname: "Mendacious Cosmonaut"
## 
##      The syntax of deldir() has had an important change. 
##      The arguments have been re-ordered (the first three 
##      are now "x, y, z") and some arguments have been 
##      eliminated.  The handling of the z ("tags") 
##      argument has been improved.
##  
##      The "dummy points" facility has been removed. 
##      This facility was a historical artefact, was really 
##      of no use to anyone, and had hung around much too 
##      long.  Since there are no longer any "dummy points", 
##      the structure of the value returned by deldir() has 
##      changed slightly.  The arguments of plot.deldir() 
##      have been adjusted accordingly; e.g. the character 
##      string "wpoints" ("which points") has been 
##      replaced by the logical scalar "showpoints". 
##      The user should consult the help files.
## Carregando pacotes exigidos: ade4
## Carregando pacotes exigidos: adehabitatMA
## Registered S3 methods overwritten by 'adehabitatMA':
##   method                       from
##   print.SpatialPixelsDataFrame sp  
##   print.SpatialPixels          sp
## Carregando pacotes exigidos: adehabitatLT
## Carregando pacotes exigidos: CircStats
## Carregando pacotes exigidos: MASS
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
## 
##     select
## Carregando pacotes exigidos: boot
## 
## Attaching package: 'adehabitatLT'
## The following object is masked from 'package:dplyr':
## 
##     id
## Carregando pacotes exigidos: knitr
## Carregando pacotes exigidos: kableExtra
## 
## Attaching package: 'kableExtra'
## The following object is masked from 'package:dplyr':
## 
##     group_rows
##    tidyverse           sf         tmap        rgdal        rgeos adehabitatHR 
##         TRUE         TRUE         TRUE         TRUE         TRUE         TRUE 
##        knitr   kableExtra 
##         TRUE         TRUE

2- CRIANDO UM OBJETO SIMPLE FEATURE (SF) A PARTIR DA BASE DE DADOS SHOPPINGS

Carregando a Base de dados shoppings:

load("shoppings.RData")

Analisando a classe do objeto shoppings:

class(shoppings)
## [1] "data.frame"

Observando as variáveis da Base de dados shoppings:

shoppings %>%
  kable() %>%
  kable_styling(bootstrap_options = "striped",
                full_width = TRUE,
                font_size = )
shopping endereco regiao latitude longitude
Boavista Shopping Rua Borba Gato 59 Santo Amaro 04747030, Sao Paulo, Brazil sul -23.65472 -46.70090
Bourbon Shopping Rua Palestra Italia 500 Perdizes 05005030, Sao Paulo, Brazil oeste -23.52655 -46.68082
Brascan Century Open Mall Rua Joaquim Floriano 466 Itaim Bibi 04534002, Sao Paulo, Brazil oeste -23.58434 -46.67502
Frei Caneca Shopping Rua Frei Caneca 569 Consolacao 01307001, Sao Paulo, Brazil central -23.55414 -46.65259
Mais Shopping Largo 13 Rua Amador Bueno 229 Santo Amaro 04752005, Sao Paulo, Brazil sul -23.65300 -46.71034
Market Place Avenida Doutor Chucri Zaidan 902 Vila Cordeiro 04795100, Sao Paulo, Brazil sul -23.62149 -46.69966
Mega Polo Moda Rua Barao de Ladario 566 Bras 03010000, Sao Paulo, Brazil central -23.53686 -46.61850
Morumbi Shopping Avenida Roque Petroni Junior 1089 Jardim das Acacias 04707900, Sao Paulo, Brazil sul -23.62336 -46.69884
Open Mall Panamby Rua Jose Ramon Urtiza 975 Vila Andrade 05717270, Sao Paulo, Brazil sul -23.63314 -46.72903
Raposo Shopping SP-270 KM 14.5 Jardim Boa Vista 05577200, Sao Paulo, Brazil oeste -23.58805 -46.75106
Santana Parque Shopping Rua Conselheiro Moreira de Barros 2780 Santana 02430001, Sao Paulo, Brazil norte -23.48282 -46.64483
Santana Shopping Rua Voluntarios da Patria 2182 Santana 02010700, Sao Paulo, Brazil norte -23.49193 -46.63287
Shopping Anália Franco Avenida Regente Feijo 1739 Tatuape 03342900, Sao Paulo, Brazil leste -23.56110 -46.56041
Shopping Aricanduva Avenida Aricanduva 5555 Jardim Marilia 03572000, Sao Paulo, Brazil leste -23.56584 -46.50203
Shopping Boulevard Tatuapé Rua Goncalves Crespo 78 Tatuape 03066030, Sao Paulo, Brazil leste -23.53915 -46.57634
Shopping Butantã Avenida Professor Francisco Morato 2718 Butanta 05512300, Sao Paulo, Brazil oeste -23.58455 -46.72514
Shopping Campo Limpo Estrada do Campo Limpo 459 Vila Prel 05777001, Sao Paulo, Brazil sul -23.64970 -46.75752
Shopping Center 3 Avenida Paulista 2064 Cerqueira Cesar 01310928, Sao Paulo, Brazil central -23.55833 -46.65947
Shopping Center Lapa Rua Catao 72 Lapa 05049901, Sao Paulo, Brazil oeste -23.52121 -46.70083
Shopping Center Norte Travessa Casalbuono 120 Vila Guilherme 02089900, Sao Paulo, Brazil norte -23.51561 -46.61805
Shopping Center Penha Rua Doutor Joao Ribeiro 304 Penha de Franca 03634900, Sao Paulo, Brazil leste -23.52530 -46.54693
Shopping Center Pirituba Avenida Benedito Andrade 71 Vila Barreto 02936000, Sao Paulo, Brazil noroeste -23.48786 -46.71992
Shopping Central Plaza Avenida Doutor Francisco Mesquita 1000 Jardim Ibitirama 03153001, Sao Paulo, Brazil leste -23.59366 -46.58569
Shopping Cidade Jardim Avenida Magalhaes de Castro 12000 Cidade Jardim 05502001, Sao Paulo, Brazil sul -23.59891 -46.69757
Shopping Cidade São Paulo Avenida Paulista 1230 Bela Vista 01310100, Sao Paulo, Brazil central -23.56364 -46.65290
Shopping D Avenida Cruzeiro do Sul 1100 Caninde 03033020, Sao Paulo, Brazil central -23.52167 -46.62392
Shopping D&D Avenida das Nacoes Unidas 12555 Brooklin 04578903, Sao Paulo, Brazil sul -23.60917 -46.69636
Shopping Eldorado Avenida Reboucas 3970 Pinheiros 05402600, Sao Paulo, Brazil oeste -23.57291 -46.69656
Shopping Fiesta Avenida Guarapiranga 752 Vila Socorro 04762001, Sao Paulo, Brazil sul -23.66503 -46.72159
Shopping Ibirapuera Avenida Ibirapuera 3103 Indianapolis 04029902, Sao Paulo, Brazil centro-sul -23.61047 -46.66664
Shopping Iguatemi Avenida Brigadeiro Faria Lima 2232 Jardim Paulistano 01489900, Sao Paulo, Brazil oeste -23.57699 -46.68814
Shopping Interlagos Avenida Interlagos 2255 Interlagos 04661200, Sao Paulo, Brazil sul -23.67651 -46.67673
Shopping Interlar Avenida Interlagos 2225 Jardim Consorcio 04661200, Sao Paulo, Brazil centro-sul -23.61898 -46.59047
Shopping Jardim Sul Rua Itacaiuna 61 Vila Andrade 05716070, Sao Paulo, Brazil sul -23.63211 -46.73568
Shopping Lar Center Avenida Otto Baumgart 500 Vila Guilherme 02049000, Sao Paulo, Brazil norte -23.51442 -46.61552
Shopping Light Rua Coronel Xavier de Toledo 23 Centro Historico de Sao Paulo 01048000, Sao Paulo, Brazil central -23.54667 -46.63877
Shopping Metrô Itaquera Avenida Jose Pinheiro Borges s/n Itaquera 08220900, Sao Paulo, Brazil leste -23.54058 -46.47064
Shopping Metrô Santa Cruz Rua Domingos de Morais 2564 Vila Mariana 04036100, Sao Paulo, Brazil centro-sul -23.59908 -46.63718
Shopping Metrô Tatuapé Rua Domingos Agostim 91 Cidade Mae do Ceu 03306010, Sao Paulo, Brazil leste -23.54038 -46.57391
Shopping Metrô Tucuruvi Rua Paranabi 218 Tucuruvi 02307120, Sao Paulo, Brazil norte -23.47987 -46.60252
Shopping Nações Unidas Avenida das Nacoes Unidas 12901 Brooklin 04578910, Sao Paulo, Brazil sul -23.61082 -46.69710
Shopping Pátio Higienópolis Rua Doutor Veiga Filho 133 Higienopolis 01238000, Sao Paulo, Brazil central -23.54228 -46.65750
Shopping Paulista Rua Treze de Maio 1947 Bela Vista 01327001, Sao Paulo, Brazil central -23.56426 -46.65091
Shopping Plaza Sul Praca Leonor Kaupa 100 Jardim da Saude 04151100, Sao Paulo, Brazil centro-sul -23.61982 -46.62704
Shopping SP Market Avenida das Nacoes Unidas 22540 Jurubatuba 04795000, Sao Paulo, Brazil sul -23.67830 -46.69842
Shopping Vila Olímpia Rua Olimpiadas 360 Vila Olimpia 04551000, Sao Paulo, Brazil sul -23.59546 -46.68679
Shopping Villa-Lobos Avenida das Nacoes Unidas 4777 Alto de Pinheiros 04795100, Sao Paulo, Brazil oeste -23.55109 -46.72182
Shopping West Plaza Avenida Francisco Matarazzo s/n Agua Branca 05003020, Sao Paulo, Brazil oeste -23.52685 -46.67417
Tietê Plaza Shopping Avenida Raimundo Pereira de Magalhaes 1465 Jardim Iris 05145000, Sao Paulo, Brazil noroeste -23.50654 -46.71848
Top Center Avenida Paulista 854 Bela Vista 01310913, Sao Paulo, Brazil central -23.56551 -46.65056

Criando um objeto do tipo sf a partir do date frame shoppings:

crs - sistema de referência de coordenadas

sf_shoppings <- st_as_sf(x = shoppings,
                         coords = c("longitude", "latitude"),
                         crs = 4326)

Analisando a classe do objeto sf_shoppings:

class(sf_shoppings)
## [1] "sf"         "data.frame"

Plotando o objeto sf de forma espacial:

(Utilização do pacote tmap)

tm_shape(shp = sf_shoppings) + 
  tm_dots(size = 1)

Adicionando uma camada de um mapa do Leafleet

tmap_mode("view")
## tmap mode set to interactive viewing
tm_shape(shp = sf_shoppings) + 
  tm_dots(col = "deepskyblue4",
          border.col = "black",
          size = 0.2,
          alpha = 0.8)

3- COMBINANDO UM OBJETO SIMPLE FEATURE COM UM SHAPEFILE

Carregando um shapefile do município de São Paulo:

shp_saopaulo <- readOGR("shapefile_municipio", "municipio_sp")
## Warning in OGRSpatialRef(dsn, layer, morphFromESRI = morphFromESRI, dumpSRS
## = dumpSRS, : Discarded datum South_American_Datum_1969 in Proj4 definition:
## +proj=utm +zone=23 +south +ellps=aust_SA +units=m +no_defs
## OGR data source with driver: ESRI Shapefile 
## Source: "C:\Users\italo\OneDrive\Área de Trabalho\##MBA DATA SCIENCE E ANALYTICS\PROJETOS ITALO\AnaliseEspacialDistanciaEntreShoppings-SP\shapefile_municipio", layer: "municipio_sp"
## with 96 features
## It has 9 fields

Visualização do shapefile de São Paulo:

tm_shape(shp = shp_saopaulo) + 
  tm_borders()

Combinando o objeto shp_saopaulo com o sf_shoppings

tm_shape(shp = shp_saopaulo) + 
  tm_borders(alpha = 0.5) + 
  tm_shape(shp = sf_shoppings)+
  tm_dots(col = "regiao",
          size = 0.2)

4- BUFFER ANALYSIS

O buffering é uma técnica utilizada para medir distâncias para fora de um dado ponto geográfico. A aplicação da técnica será feita por meio da função gBuffer(), do pacote rgeos.

A função gBuffer não funciona com objetos do tipo simple feature. Portanto, para utilizá-la, iremos converter o objeto sf_shoppings para um objeto do tipo spatial points (sp).

Convertendo sf_shoppings para objeto do tipo sp:

a- Isolando as coordenadas do date frame original:

coord_shoppings <- cbind(shoppings$longitude,
                         shoppings$latitude)

b- Criando o objeto sp:

sp_shoppings <- SpatialPoints(coords = coord_shoppings,
                              proj4string = CRS("+proj=longlat"))

Visualizando o resultado:

tmap_mode("plot")
## tmap mode set to plotting
tm_shape(shp = sp_shoppings) + 
  tm_dots(size = 1)

Além de exigir um objeto da classe sp, a função gBuffer() exige também que o objeto se oriente por distâncias euclidianas. O objeto atual se orienta de forma geodésica. Vamos tranformá-lo:

shopping_UTM <- spTransform(x = sp_shoppings,
                            CRSobj = CRS("+init=epsg:22523"))
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
## prefer_proj): Discarded datum Corrego_Alegre_1970-72 in Proj4 definition

Agora, podemos aplicar a função gBuffer():

buffer_shoppings <- gBuffer(spgeom = shopping_UTM,
                            width = 1500,
                            byid = TRUE)

Plotando buffer_shoppings:

tmap_mode("view")
## tmap mode set to interactive viewing
tm_shape(shp = buffer_shoppings) +
  tm_borders()

Combinando os objetos shp_saopaulo, sf_shoppings e buffer_shoppings:

tm_shape(shp = shp_saopaulo) + 
  tm_borders(alpha = 0.5) + 
  tm_shape(shp = sf_shoppings)+
  tm_dots(col = "regiao",
          size = 0.2) +
  tm_shape(shp = buffer_shoppings) +
  tm_borders(col = "black")

5- BUFFER UNION

A técnica de buffer union combina os outputs da técnica de buffering que, por ventura, se encontrem.

buffer_union <- gUnaryUnion(spgeom = buffer_shoppings)

tm_shape(shp = shp_saopaulo) + 
  tm_borders(alpha = 0.5) + 
  tm_shape(shp = sf_shoppings)+
  tm_dots(col = "regiao",
          size = 0.2) +
  tm_shape(shp = buffer_shoppings) +
  tm_borders(col = "black") + 
  tm_fill(col = "red",
          alpha = 0.3)

6- Kernel Densities

A técnica de kernel densities calcula a densidade da presença de pontos de interesse em determina área geográfica.

a- Precisaremos criar um objeto sp com a base de dados atrelada a ele:

shoppings_sp_df <- SpatialPointsDataFrame(data = shoppings,
                                          coords = coord_shoppings,
                                          proj4string = CRS("+proj=longlat"))

b- Para cálculo das kernel densities, iremos utilizar a função kernelUD():

shoppings_dens <- kernelUD(xy = shoppings_sp_df,
                           h = "href",
                           grid = 1000,
                           boundary = NULL)
## Warning in proj4string(xy): CRS object has comment, which is lost in output; in tests, see
## https://cran.r-project.org/web/packages/sp/vignettes/CRS_warnings.html
## Warning in kernelUD(xy = shoppings_sp_df, h = "href", grid = 1000, boundary = NULL): xy should contain only one column (the id of the animals)
## id ignored
## Warning in proj4string(xy): CRS object has comment, which is lost in output; in tests, see
## https://cran.r-project.org/web/packages/sp/vignettes/CRS_warnings.html
plot(shoppings_dens)

c- Para estabelecer as zonas com maior densidade, propomos o seguinte:

zona1 <- getverticeshr(x = shoppings_dens, percent = 20)
## Warning in proj4string(x): CRS object has comment, which is lost in output; in tests, see
## https://cran.r-project.org/web/packages/sp/vignettes/CRS_warnings.html

## Warning in proj4string(x): CRS object has comment, which is lost in output; in tests, see
## https://cran.r-project.org/web/packages/sp/vignettes/CRS_warnings.html
zona2 <- getverticeshr(x = shoppings_dens, percent = 40)
## Warning in proj4string(x): CRS object has comment, which is lost in output; in tests, see
## https://cran.r-project.org/web/packages/sp/vignettes/CRS_warnings.html

## Warning in proj4string(x): CRS object has comment, which is lost in output; in tests, see
## https://cran.r-project.org/web/packages/sp/vignettes/CRS_warnings.html
zona3 <- getverticeshr(x = shoppings_dens, percent = 60)
## Warning in proj4string(x): CRS object has comment, which is lost in output; in tests, see
## https://cran.r-project.org/web/packages/sp/vignettes/CRS_warnings.html

## Warning in proj4string(x): CRS object has comment, which is lost in output; in tests, see
## https://cran.r-project.org/web/packages/sp/vignettes/CRS_warnings.html
zona4 <- getverticeshr(x = shoppings_dens, percent = 80)
## Warning in proj4string(x): CRS object has comment, which is lost in output; in tests, see
## https://cran.r-project.org/web/packages/sp/vignettes/CRS_warnings.html

## Warning in proj4string(x): CRS object has comment, which is lost in output; in tests, see
## https://cran.r-project.org/web/packages/sp/vignettes/CRS_warnings.html
tmap_options(check.and.fix = TRUE)

tm_shape(shp = shp_saopaulo) + 
  tm_fill(col = "gray90") + 
  tm_borders(col = "white", alpha = 0.5) + 
  tm_shape(shp = shoppings_sp_df) + 
  tm_dots(col = "regiao", size = 0.25) + 
  tm_shape(zona1) + 
  tm_borders(col = "firebrick4", lwd = 2.5) +
  tm_fill(alpha = 0.4, col = "firebrick4") + 
  tm_shape(zona2) + 
  tm_borders(col = "firebrick3", lwd = 2.5) + 
  tm_fill(alpha = 0.3, col = "firebrick3") + 
  tm_shape(zona3) + 
  tm_borders(col = "firebrick2", lwd = 2.5) + 
  tm_fill(alpha = 0.2, col = "firebrick2") +
  tm_shape(zona4) + 
  tm_borders(col = "firebrick1", lwd = 2.5) + 
  tm_fill(alpha = 0.1, col = "firebrick1")
## Warning: The shape zona1 is invalid. See sf::st_is_valid
## Warning: The shape zona2 is invalid. See sf::st_is_valid
## Warning: The shape zona3 is invalid. See sf::st_is_valid
## Warning: The shape zona4 is invalid. See sf::st_is_valid